package com.kgc.servlet;

import com.alibaba.fastjson.JSONObject;
import com.kgc.entity.Role;
import com.kgc.entity.User;
import com.kgc.service.UserService;
import com.kgc.service.impl.UserServiceImpl;
import com.kgc.util.FileUtil;
import com.kgc.util.UUIDUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        //接受mode
        String mode = request.getParameter("mode");

        if("login".equals(mode)){
            //调用登录
            this.login(request,response);
        }else if("loginout".equals(mode)){
            //退出
            this.loginout(request,response);
        }else if("listUser".equals(mode)){
            //用户列表
            this.listUsers(request, response);
        }else if("findById".equals(mode)){
            //查看用户
            this.findById(request, response);
        }else if("insert".equals(mode)){
            //添加用户信息
            this.insertUser(request, response);

        }else if("delete".equals(mode)){
            this.delete(request, response);
        }else if("toUpdate".equals(mode)){
            this.toUpdate(request, response);
        }else if("update".equals(mode)){
            this.updateUser(request, response);
        }
    }

    /**
     * 修改用户
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        User u = null;
        try {
            List<FileItem> list = upload.parseRequest(request);
            for(FileItem fi : list){
                //判定普通表单还是文件表单
                if(fi.isFormField()){
                    //获取表单name属性值 和 对应值
                    String name = fi.getFieldName();
                    String value = fi.getString("utf-8");
                    if("id".equals(name)){
                        u = userService.getUserById(Integer.parseInt(value));
                    }else if("userName".equals(name)){
                        u.setUsername(value);
                    }else if("gender".equals(name)){
                        u.setGender(Integer.parseInt(value));
                    }else if("birthday".equals(name)){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date d = sdf.parse(value);
                        u.setBirthday(d);
                    }else if("phone".equals(name)){
                        u.setPhone(value);
                    }else if("address".equals(name)){
                        u.setAddress(value);
                    }else if("userRole".equals(name)){
                        Role r = new Role();
                        r.setId(Integer.parseInt(value));
                        u.setRole(r);
                    }
                }else{
                    //修改
                    if(fi.getSize() > 0) {
                        //表示用户上传了新的照片
                        //文件
                        //获取应用的绝对地址
                        ServletContext application = this.getServletContext();
                        //获取发布项目的跟路径
                        String rootPath = application.getRealPath("/");
                        //文件夹路径
                        String dirPath = "uploadImg";

                        //读图片
                        InputStream is = fi.getInputStream();
                        byte[] b = new byte[(int) fi.getSize()];
                        is.read(b, 0, b.length);

                        //文件名
                        String fileName = fi.getName();
                        String uuid = UUIDUtil.createUUID();
                        String newName = uuid + fileName.substring(fileName.lastIndexOf("."));
                        String photoPath = rootPath + dirPath + "/" + newName;
                        FileOutputStream fos = new FileOutputStream(photoPath);
                        fos.write(b);
                        fos.flush();
                        fos.close();


                        String formName = fi.getFieldName();
                        if ("cardphoto".equals(formName)) {
                            //删除原照片
                            String oldPath = u.getCardphoto();
                            FileUtil.deleteFile(oldPath, rootPath);
                            //给与新的地址
                            u.setCardphoto(dirPath + "/" + newName);
                        } else {
                            //删除老工作照
                            String oldPath = u.getWorkphoto();
                            FileUtil.deleteFile(oldPath, rootPath);
                            u.setWorkphoto(dirPath + "/" + newName);
                        }
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        //设置修改人
        u.setModifyby(loginUser.getId());
        //修改日期
        u.setModifydate(new Date());
        int flag = userService.updateUser(u);
        request.setAttribute("updateFlag",flag);
        request.getRequestDispatcher("userlist.jsp").forward(request,response);

    }


    /**
     * 跳转到用户修改页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //接受id
        int id = Integer.parseInt(request.getParameter("id"));
        //根据id获取对象
        User u = userService.getUserById(id);
        request.setAttribute("user",u);
        request.getRequestDispatcher("usermodify.jsp").forward(request,response);

    }

    /**
     * 删除
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取id
        int id = Integer.parseInt(request.getParameter("id"));
        //获取应用的绝对地址
        ServletContext application = this.getServletContext();
        //获取发布项目的跟路径
        String rootPath = application.getRealPath("/");
        int flag = userService.deleteUserById(id,rootPath);
        request.setAttribute("deleteFlag",flag);
        request.getRequestDispatcher("userlist.jsp").forward(request,response);
    }


    /**
     * 添加
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void insertUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try {
            //创建FileItemFactory对象
            FileItemFactory factory = new DiskFileItemFactory();
            //创建ServletFileupload
            ServletFileUpload upload = new ServletFileUpload(factory);
            //解析request
            List<FileItem> list = upload.parseRequest(request);
            //创建User对象
            User u = new User();
            for(FileItem fi : list){
                //判定普通表单还是文件表单
                if(fi.isFormField()){
                    //普通文本
                    //获取表单的name 和对应的value
                    String name = fi.getFieldName();
                    String value = fi.getString("utf-8");
                    if("userCode".equals(name)){
                        u.setUsercode(value);
                    }else if("userName".equals(name)){
                        u.setUsername(value);
                    }else if("userPassword".equals(name)){
                        u.setUserpassword(value);
                    }else if("gender".equals(name)){
                        u.setGender(Integer.parseInt(value));
                    }else if("birthday".equals(name)){
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date d = sdf.parse(value);
                        u.setBirthday(d);
                    }else if("phone".equals(name)){
                        u.setPhone(value);
                    }else if("address".equals(name)){
                        u.setAddress(value);
                    }else if("userRole".equals(name)){
                        Role r = new Role();
                        r.setId(Integer.parseInt(value));
                        u.setRole(r);
                    }

                }else{
                    //文件
                    //获取应用的绝对地址
                    ServletContext application = this.getServletContext();
                    //获取发布项目的跟路径
                    String rootPath = application.getRealPath("/");
                    System.out.println(rootPath);
                    //创建文件夹
                    String dirName = "uploadImg";
                    String dirPath = rootPath + dirName;
                    File dirFile = new File(dirPath);
                    if(!dirFile.exists()){
                        dirFile.mkdir();
                    }

                    //获取文件名
                    String photoName = fi.getName();
                    //获取全球唯一号
                    String uuid = UUIDUtil.createUUID();
                    String newName = uuid + photoName.substring(photoName.lastIndexOf("."));
                    //获取文件流
                    InputStream is = fi.getInputStream();
                    byte[] b = new byte[(int) fi.getSize()];
                    is.read(b,0,b.length);

                    //写文件
                    String photoPath = dirPath + "/" + newName;
                    FileOutputStream fos = new FileOutputStream(photoPath);
                    fos.write(b);
                    fos.flush();
                    fos.close();

                    //获取表单的name
                    String name = fi.getFieldName();
                    if("cardphoto".equals(name)){

                        u.setCardphoto(dirName + "/" +newName);
                    }else {

                        u.setWorkphoto(dirName + "/" +newName);
                    }

                }
            }
            //调用保存
            HttpSession session = request.getSession();
            User loginUser = (User) session.getAttribute("loginUser");
            //创建人
            u.setCreateby(loginUser.getId());
            //创建时间
            u.setCreationdate(new Date());
            int flag = userService.insertUser(u);
            request.setAttribute("insertFlag",flag);
            request.getRequestDispatcher("useradd.jsp").forward(request,response);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }



    /**
     * 根据id查询
     * @param request
     * @param response
     */
    private void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //获取id
        int id = Integer.parseInt(request.getParameter("id"));
        User u = userService.getUserById(id);
        request.setAttribute("user",u);
        request.getRequestDispatcher("userview.jsp").forward(request,response);
    }

    /**
     * 登录
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //接值
        String username = request.getParameter("username");
        String userpassword = request.getParameter("userpassword");
        //调用service获取数据
        User user = userService.getUserByUsername(username);
        String resultView = "index.jsp";
        if(user != null){
            //判定密码
            String sysPassword = user.getUserpassword();
            if(sysPassword.equals(userpassword)){
                //密码正确
                resultView = "frame.jsp";
                //用户登录信息存放session
                HttpSession session = request.getSession();
                session.setAttribute("loginUser",user);
            }else{
                //密码错误
                request.setAttribute("passwordFlag","密码输入不正确");
            }
        }else{
            //用户不存在
            request.setAttribute("usernameFlag","用户不存在");
        }

        request.getRequestDispatcher(resultView).forward(request,response);

    }

    /**
     * 退出
     * @param request
     * @param response
     */
    private void loginout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //移除session中登录信息
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");
        //回首页
        response.sendRedirect("index.jsp");
    }


    /**
     * ajax查询用户列表
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void listUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //接值

        String name = request.getParameter("name");
        String userRole = request.getParameter("userRole");
        //接受当前页码数

        int currentPage = Integer.parseInt(request.getParameter("currentPage"));

        //获取列表数据
        List<User> list = userService.listUsers(name,userRole,currentPage);
        //总记录数
        int totalCount = userService.countUsers(name,userRole);
        //总页数
        int totalPage = totalCount % 4 == 0 ? totalCount / 4 : totalCount / 4 + 1;
        //封装map
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("list",list);
        resultMap.put("totalCount",totalCount);
        resultMap.put("totalPage",totalPage);

        String json = JSONObject.toJSONString(resultMap);
        //转json
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }

}
